package com.hongkzh.www.adv.service;

import com.google.common.collect.Lists;
import com.hongkzh.www.conmon.MathRandom;
import com.hongkzh.www.conmon.RedisTool;
import com.hongkzh.www.conmon.StaticPublic;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.params.geo.GeoRadiusParam;

import java.util.LinkedList;
import java.util.List;

/**
 * @author martins
 */
public class MediaService extends BaseService {

    static AdvService advService=new AdvService();
    public List<Record> getCarouselList() {
        SqlPara sqlPara = Db.getSqlPara("media.getCarouselList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }


    public List<Record> categoryList() {
        SqlPara sqlPara = Db.getSqlPara("media.categoryList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public List<Record> getTop10List() {
        SqlPara sqlPara = Db.getSqlPara("media.getTop10List");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public Page<Record> getHotAdvList(int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("media.getHotAdvList");
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        List<Record>  statics= advService.getStaticListByType("1");
        LinkedList<Record> llist=new LinkedList<>();
        for (Record r : records.getList()) {
            r.set("advType",1);
            doFilePath(r);
            llist.add(r);
            for (Record static1:statics
                    ) {
                if(0==MathRandom.PercentageRandom()) {
                    static1.set("advType",2);
                    llist.add(static1);
                    break;
                }
            }
        }
        Page<Record>   records2=new Page<Record>(llist,records.getPageNumber(),records.getPageSize(),records.getTotalPage(),records.getTotalRow());


        return records2;

    }

    private void initMediaData() {

        if (!RedisTool.exists(StaticPublic.GEOMEDIAEXITSKEY)) {
            RedisTool.del(StaticPublic.GEOMEDIAKEY);
            SqlPara sqlPara = Db.getSqlPara("media.getMediaAdvList");
            List<Record> records = Db.find(sqlPara);
            if (null != records && records.size() > 0) {
                RedisTool.setex(StaticPublic.GEOMEDIAEXITSKEY, StaticPublic.GEOMEDIAEXITSKEYTIME, "1");
                for (Record r : records) {
                    RedisTool.geoadd(StaticPublic.GEOMEDIAKEY, r.getDouble("longitude"), r.getDouble("latitude"), r.getStr("id"));
                }
            }

        }
    }

    public Page<Record> getNearbyAdvList(double latitude, double longitude, int pageNumber) {

        initMediaData();

        List<Record> records = Lists.newArrayList();
        Page<Record> p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, 0, 0);
        List<GeoRadiusResponse> list = RedisTool.georadius(StaticPublic.GEOMEDIAKEY, longitude, latitude, StaticPublic.BAI, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().sortAscending().count(6 * pageNumber));
        int totalRow = list.size();

        int totalPage = (int) (totalRow / StaticPublic.PAGESIZE);
        if (null != list && list.size() > 0) {
            list.subList(0, StaticPublic.PAGESIZE * (pageNumber - 1)).clear();
        }
        SqlPara sqlPara;
        List<Record>  statics= advService.getStaticListByType("1");

        for (GeoRadiusResponse g : list) {
            String id = new String(g.getMember());
            sqlPara = Db.getSqlPara("media.getMediaAdvById", id);
            Record r = Db.findFirst(sqlPara);
            if (null != r) {
                r.set("advType",1);
                r.set("distance", g.getDistance());
                doFilePath(r);

                records.add(r);
                for (Record static1:statics
                        ) {
                    if(0==MathRandom.PercentageRandom()) {
                        static1.set("advType",2);
                        records.add(static1);
                        break;
                    }
                }
            }
        }
        if (null != records && records.size() > 0) {
            p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, totalPage, totalRow);
        }
        return p;
    }

    public List<Record> getHotNewsList() {
        SqlPara sqlPara = Db.getSqlPara("media.getHotNewsList");
        return Db.find(sqlPara);
    }

    public List<Record> getCirclesList() {
        SqlPara sqlPara = Db.getSqlPara("media.getCirclesList");
        return Db.find(sqlPara);
    }


    public List<Record> AllCategoryList() {
        SqlPara sqlPara = Db.getSqlPara("media.ALLCategoryList");
        List<Record> records = Db.find(sqlPara);
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public List<Record> getCategoryCarouselList(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryCarouselList", categoryId);
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }


    public List<Record> getCategoryTop10List(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryTop10List", categoryId);
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public Page<Record> getCategoryHotAdvList(int pageNumber, String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryHotAdvList", categoryId);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record>  statics= advService.getStaticListByType("1");
        LinkedList<Record> llist=new LinkedList<>();
        for (Record r : records.getList()) {
            r.set("advType",1);
            doFilePath(r);
            llist.add(r);
            for (Record static1:statics
                    ) {
                if(0==MathRandom.PercentageRandom()) {
                    static1.set("advType",2);
                    llist.add(static1);
                    break;
                }
            }
        }
        Page<Record>   records2=new Page<Record>(llist,records.getPageNumber(),records.getPageSize(),records.getTotalPage(),records.getTotalRow());


        return records2;
    }

    private void initMediaDataByCategory(String categoryId) {
        String key = String.format(StaticPublic.GEOMEDIAEXITSKEYCATEGORY, categoryId);
        String categoryKey = String.format(StaticPublic.GEOMEDIAKEYCATEGORY, categoryId);
        if (!RedisTool.exists(key)) {
            RedisTool.del(categoryKey);
            SqlPara sqlPara = Db.getSqlPara("media.getMediaAdvCategoryList", categoryId);
            List<Record> records = Db.find(sqlPara);
            if (null != records && records.size() > 0) {
                RedisTool.setex(key, StaticPublic.GEOMEDIAEXITSKEYTIME, "1");
                for (Record r : records) {
                    RedisTool.geoadd(categoryKey, r.getDouble("longitude"), r.getDouble("latitude"), r.getStr("id"));
                }
            }

        }
    }

    public Page<Record> getCategoryNearbyAdvList(double latitude, double longitude, int pageNumber, String categoryId) {
        String categoryKey = String.format(StaticPublic.GEOMEDIAKEYCATEGORY, categoryId);
        initMediaDataByCategory(categoryId);

        List<Record> records = Lists.newArrayList();
        Page<Record> p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, 0, 0);
        List<GeoRadiusResponse> list = RedisTool.georadius(categoryKey, longitude, latitude, StaticPublic.BAI, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().sortAscending().count(6 * pageNumber));
        int totalRow = list.size();

        int totalPage = (int) (totalRow / StaticPublic.PAGESIZE);
        if (null != list && list.size() > 0) {
            list.subList(0, StaticPublic.PAGESIZE * (pageNumber - 1)).clear();
        }
        SqlPara sqlPara;

        List<Record>  statics= advService.getStaticListByType("1");



        for (GeoRadiusResponse g : list) {
            String id = new String(g.getMember());
            sqlPara = Db.getSqlPara("media.getMediaAdvById", id);
            Record r = Db.findFirst(sqlPara);
            if (null != r) {
                r.set("advType",1);
                r.set("distance", g.getDistance());
                doFilePath(r);

                records.add(r);
                for (Record static1:statics
                        ) {
                    if(0==MathRandom.PercentageRandom()) {
                        static1.set("advType",2);
                        records.add(static1);
                        break;
                    }
                }
            }
        }
        if (null != records && records.size() > 0) {
            p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, totalPage, totalRow);
        }
        return p;

    }

    public List<Record> getCategoryQueryList(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryQueryList", categoryId);
        List<Record> records = Db.find( sqlPara);
        return records;
    }

    public List<Record> getCategoryOrdinaryList(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryOrdinaryList", categoryId);
        List<Record> records = Db.find( sqlPara);
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }
    public List<Record> getCategoryCirclesList(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryCirclesList", categoryId);
        return Db.find(sqlPara);
    }

    public Page<Record> getCategoryCirclesList(String categoryId, int pageNumber, String sortId, String sortValue) {
        if("create_date".equals(sortId)) {sortId=" a.create_date ";}
        else if("user_count".equals(sortId)){ sortId=" b.user_count ";}
        Kv cond=Kv.by("categoryId",categoryId).set("order", " order by "+ sortId+" "+sortValue);
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryCirclesList",cond);
        Page<Record> records=Db.paginate(pageNumber,StaticPublic.PAGESIZE,sqlPara);

        for (Record r:records.getList()) {
            doFilePath(r);

        }
        return records;
    }

    public Page<Record> getInfoMediaAdvCommentList(int pageNumber, String id, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("media.getInfoMediaAdvCommentList",id);
        Page<Record> records=Db.paginate(pageNumber,StaticPublic.PAGESIZE,sqlPara);

        return records;

    }

    public Record getAdvById(String id, String userId) {
        {
            SqlPara sqlPara = Db.getSqlPara("media.getAdvById", id,userId);
            Record r = Db.findFirst(sqlPara);
            if (r != null) {
                r.set("collectionState","0");
                if(StrKit.notBlank(r.getStr("collectionId"))){
                    r.set("collectionState","1");
                }
                r.set("praiseState","0");
                if(StrKit.notBlank(r.getStr("praiseId"))){
                    r.set("praiseState","1");
                }

                doFilePath(r);
            }

            return r;

        }
    }
}
